{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 1. 要么是元类，要么不是元类  \n",
    "元类主要是针对那些构建API和工具供他人使用的程序员。  \n",
    "\n",
    "## 1.1 提高魔力层次  \n",
    "元类允许我们在一条 class 语句的末尾，插入当创建一个类对象的时候自动运行的逻辑。这个逻辑不会把类名重新绑定到一个装饰器可调用对象，而是把类自身的创建指向特定的逻辑。  \n",
    "\n",
    "## 1.2 “辅助”函数的缺点  \n",
    "元类常常是可选的，我们通常可以通过管理器函数（有时候叫做“辅助”函数）传递类对象来实现同样的效果，这和我们通过管理器代码传递函数和实例来实现装饰器的目的很相似。  \n",
    "\n",
    "然而，元类：\n",
    "- 提供一种更为正式和明确的结构。\n",
    "- 有助于确保应用程序员不会忘记根据一个 API 需求来扩展他们的类。\n",
    "- 通过把类定制逻辑工厂化到一个单独的位置（元类）中，避免代码冗余及其相关的维护成本。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 2. 元类模型  \n",
    "## 2.1 类是 type 的实例  \n",
    "在 Python 3 中，用户定义的类对象是名为 type 的对象的实例， type 本身是一个类。  \n",
    "\n",
    "type 内置函数返回任何对象的类型（它本身是一个对象）。对于列表这样的内置类型，实例的类型是一个内置的列表类型，但是，列表类型的类型是类型 type 自身——顶层的 type 对象创建了具体的类型，具体的类型创建了实例。  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(list, type)"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type([]), type(type([]))     # 列表实例由列表类创建，列表类由 type 类创建"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(type, type)"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type(list), type(type)       # type 的类型是 type"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "实例创建自类，而类创建自 type。在 Python 3 中，类型与类的概念合并了 —— class 是 type，type 也是 class：\n",
    "- 类型由派生自 type 的类定义。\n",
    "- 用户定义的类是类型类的实例。\n",
    "- 用户定义的类是产生它们自己的实例的类型。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "__main__.C"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "class C: pass\n",
    "\n",
    "X = C()              # 类实例对象\n",
    "type(X)              # 实例是类的实例"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "__main__.C"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X.__class__          # 实例的类"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "type"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type(C)              # 类是 type 的实例"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "type"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "C.__class__          # 类的类是 type"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2.2 元类是 Type 的子类  \n",
    "由于类实际上是 type 类的实例，从 type 的定制的子类创建类允许我们实现各种定制的类。\n",
    "- type 是产生用户定义的类的一个类。\n",
    "- 元类是 type 类的一个子类。\n",
    "- 类对象是 type 类的一个实例，或一个子类。\n",
    "- 实例对象产生自一个类。  \n",
    "\n",
    "## 2.3 Class 语句协议  \n",
    "当 Python 遇到一条 class 语句，它会运行其嵌套的代码块以创建其属性——所有在嵌套代码块的顶层分配的名称都生成类对象中的属性。这些名称通常是嵌套的 def 所创建的方法函数，但是，它们也可以是分配来创建由所有实例共享的类数据的任意属性。  \n",
    "\n",
    "Python 遵从一个标准的协议来使这发生：在**一条class语句的末尾**，并且在运行了一个命名空间词典中的所有嵌套代码之后，它调用 type 对象来创建 class 对象："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class = type(classname, superclasses, attributedict)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "type 对象反过来定义了一个 `__call__` 运算符重载方法，当调用 type 对象的时候，该方法运行两个其他的方法："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "type.__new__(typeclass, classname, superclasses, attributedict)\n",
    "type.__init__(class, classname, superclasses, attributedict)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`__new__` 方法创建并返回了新的 class 对象，并且随后 `__init__` 方法初始化了新创建的对象。这是 type 的元类子类通常用来定制类的钩子。例如："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Eggs:\n",
    "    pass\n",
    "\n",
    "class Span(Eggs):          # 从 Eggs 继承\n",
    "    data = 1               # 类数据属性\n",
    "    def meth(self, arg):   # 类方法属性\n",
    "        return self.data + arg"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Python 将会从内部运行嵌套的代码块来创建该类的两个属性（data 和 meth），然后在 class 语句的末尾调用 type 对象，产生 class 对象："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "Spam = type('Spam', (Eggs,), {'data': 1, 'meth': meth, '__module__': '__main__'})"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "你可以以这种方式调用 `type` 来动态创建类："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(__main__.Spam, <__main__.Spam at 0x1b9dc0aaa90>)"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x = type('Spam', (), {'data': 1, 'meth': (lambda x, y: x.data + y)})\n",
    "i = x()\n",
    "x, i"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(1, 3)"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "i.data, i.meth(2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "生成的类和运行 `class` 语句得到的类完全一样："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(object,)"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x.__bases__"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[('data', 1), ('meth', <function __main__.<lambda>(x, y)>)]"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "[(a, v) for (a, v) in x.__dict__.items() if not a.startswith('__')]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "由于这个调用在 class 语句的末尾进行，它是用来扩展或处理一个类的、理想的钩子。技巧在于，用将要拦截这个调用的一个定制子类来替代 type。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 3. 声明元类  \n",
    "在类标题中把想要的元类作为一个关键字参数列出来："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Spam(metaclass=Meta):"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "继承超类也可以列在标题中，在元类之前。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Spam(Eggs, metaclass=Meta):"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "当以这些方式声明的时候，创建类对象的调用在 class 语句的底部运行，修改为调用元类而不是默认的 type ："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class = Meta(classname, superclasses, attributedict)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "由于元类是 type 的一个子类，所以 type 类的 `__call__` 把创建和初始化新的类对象的调用委托给元类，如果它定义了这些方法的定制版本："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "Meta.__new__(Meta, classname, superclasses, attributedict)\n",
    "Meta.__init__(class, classname, superclasses, attributedict)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 4. 编写元类  \n",
    "## 4.1 基本元类  \n",
    "最简单元类只是带有一个 `__new__` 方法的 type 的子类，该方法通过运行 type 中的默认版本来创建类对象。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Meta(type):\n",
    "    def __new__(meta, classname, supers, classdict):\n",
    "        # 通过继承的 type.__call__ 调用\n",
    "        return type.__new__(meta, classname, supers, classdict)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "由于元类在一条 class 语句的末尾调用，并且因为 type 对象的 `__call__` 分派到了 `__new__` 和 `__init__` 方法，所以我们在这些方法中提供的代码可以管理从元类创建的所有类。  \n",
    "\n",
    "下面是应用中的实例，将打印添加到元类和文件以便追踪："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "making class\n",
      "In MetaOne.new:\n",
      "...Spam\n",
      "...(<class '__main__.Eggs'>,)\n",
      "...{'__module__': '__main__', '__qualname__': 'Spam', 'data': 1, 'meth': <function Spam.meth at 0x0000027BA26AB6A8>}\n",
      "making instance\n",
      "data: 1 3\n"
     ]
    }
   ],
   "source": [
    "class MetaOne(type):\n",
    "    def __new__(meta, classname, supers, classdict):\n",
    "        print('In MetaOne.new:', classname, supers, classdict, sep='\\n...')\n",
    "        return type.__new__(meta, classname, supers, classdict)\n",
    "\n",
    "class Eggs:\n",
    "    pass\n",
    "\n",
    "print('making class')\n",
    "class Spam(Eggs, metaclass=MetaOne):          # 继承自 Eggs，是 MetaOne 的实例\n",
    "    data = 1\n",
    "    def meth(self, arg):\n",
    "        return self.data + arg\n",
    "\n",
    "print('making instance')\n",
    "X = Spam()\n",
    "print('data:', X.data, X.meth(2))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4.2 定制构建和初始化  \n",
    "元类也可以接入 `__init__` 协议，由 type 对象的 `__call__` 调用：通常，`__new__` 创建并返回类对象，`__init__` 初始化已经创建的类。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "making class\n",
      "In MetaOne.new: \n",
      "...Spam\n",
      "...(<class '__main__.Eggs'>,)\n",
      "...{'__module__': '__main__', '__qualname__': 'Spam', 'data': 1, 'meth': <function Spam.meth at 0x0000027BA26AB950>}\n",
      "In MetaOne.init: \n",
      "...Spam\n",
      "...(<class '__main__.Eggs'>,)\n",
      "...{'__module__': '__main__', '__qualname__': 'Spam', 'data': 1, 'meth': <function Spam.meth at 0x0000027BA26AB950>}\n",
      "...init class object: ['__module__', 'data', 'meth', '__doc__']\n",
      "making instance\n",
      "data: 1 3\n"
     ]
    }
   ],
   "source": [
    "class MetaTwo(type):\n",
    "    def __new__(meta, classname, supers, classdict):\n",
    "        print('In MetaOne.new: ', classname, supers, classdict, sep='\\n...')\n",
    "        return type.__new__(meta, classname, supers, classdict)\n",
    "    \n",
    "    def __init__(Class, classname, supers, classdict):\n",
    "        print('In MetaOne.init: ', classname, supers, classdict, sep='\\n...')\n",
    "        print('...init class object:', list(Class.__dict__.keys()))\n",
    "\n",
    "class Eggs:\n",
    "    pass\n",
    "\n",
    "print('making class')\n",
    "class Spam(Eggs, metaclass=MetaTwo):\n",
    "    data = 1\n",
    "    def meth(self, arg):\n",
    "        return self.data + arg\n",
    "\n",
    "print('making instance')\n",
    "X = Spam()\n",
    "print('data:', X.data, X.meth(2))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "类初始化方法在类构建方法之后运行，但是，两者都在 class 语句最后运行，并且在创建任何实例之前运行。Spam 中的 `__init__` 方法在实例创建时运行，且不会通过元类的 `__init__` 运行。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4.3 其他元类编程技巧  \n",
    "\n",
    "**使用简单的工厂函数**  \n",
    "\n",
    "元类不是真的需要是类，**任何可调用对象**都可以用作一个元类，只要它接收传递的参数并且返回与目标类兼容的一个对象。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "making class\n",
      "In MetaFunc: \n",
      "...Spam\n",
      "...(<class '__main__.Eggs'>,)\n",
      "...{'__module__': '__main__', '__qualname__': 'Spam', 'data': 1, 'meth': <function Spam.meth at 0x0000027BA26ABA60>}\n",
      "making instance\n",
      "data: 1 3\n"
     ]
    }
   ],
   "source": [
    "# 一个简单的函数也可以像元类一样工作\n",
    "def MetaFunc(classname, supers, classdict):\n",
    "    print('In MetaFunc: ', classname, supers, classdict, sep='\\n...')\n",
    "    return type(classname, supers, classdict)\n",
    "\n",
    "class Eggs:\n",
    "    pass\n",
    "\n",
    "print('making class')\n",
    "class Spam(Eggs, metaclass=MetaFunc):       # 在类最后运行简单函数\n",
    "    data = 1\n",
    "    def meth(self, arg):\n",
    "        return self.data + arg\n",
    "\n",
    "print('making instance')\n",
    "X = Spam()\n",
    "print('data:', X.data, X.meth(2))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**用常规类重载类创建调用**  \n",
    "\n",
    "因为常规类实例可以响应操作符重载的调用操作，所以它们也可以在某些元类角色中发挥作用。下面的输出类似于以前的基于类的版本，但是它基于一个简单的类——一个根本不继承 type 的类，并且为它的实例提供一个 `__call__`，该调用使用常规操作符重载捕获元类调用。  \n",
    "\n",
    "注意 `__new__` 和 `__init__` 必须有不同的名称，否则它们将在创建 Meta 实例时运行。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "making class\n",
      "In MetaObj.call: \n",
      "...Spam\n",
      "...(<class '__main__.Eggs'>,)\n",
      "...{'__module__': '__main__', '__qualname__': 'Spam', 'data': 1, 'meth': <function Spam.meth at 0x0000027BA26AB378>}\n",
      "In MetaObj.new: \n",
      "...Spam\n",
      "...(<class '__main__.Eggs'>,)\n",
      "...{'__module__': '__main__', '__qualname__': 'Spam', 'data': 1, 'meth': <function Spam.meth at 0x0000027BA26AB378>}\n",
      "In MetaObj.init: \n",
      "...Spam\n",
      "...(<class '__main__.Eggs'>,)\n",
      "...{'__module__': '__main__', '__qualname__': 'Spam', 'data': 1, 'meth': <function Spam.meth at 0x0000027BA26AB378>}\n",
      "...init class object: ['__module__', 'data', 'meth', '__doc__']\n",
      "making instance\n",
      "data: 1 3\n"
     ]
    }
   ],
   "source": [
    "# 一个普通类实例可以作为元类\n",
    "\n",
    "class MetaObj:\n",
    "    def __call__(self, classname, supers, classdict):\n",
    "        print('In MetaObj.call: ', classname, supers, classdict, sep='\\n...')\n",
    "        Class = self.__New__(classname, supers, classdict)\n",
    "        self.__Init__(Class, classname, supers, classdict)\n",
    "        return Class\n",
    "    \n",
    "    def __New__(self, classname, supers, classdict):\n",
    "        print('In MetaObj.new: ', classname, supers, classdict, sep='\\n...')\n",
    "        return type(classname, supers, classdict)\n",
    "    \n",
    "    def __Init__(self, Class, classname, supers, classdict):\n",
    "        print('In MetaObj.init: ', classname, supers, classdict, sep='\\n...')\n",
    "        print('...init class object:', list(Class.__dict__.keys()))\n",
    "        \n",
    "class Eggs:\n",
    "    pass\n",
    "\n",
    "print('making class')\n",
    "class Spam(Eggs, metaclass=MetaObj()):      # MetaObj 是普通类实例\n",
    "    data = 1\n",
    "    def meth(self, arg):\n",
    "        return self.data + arg\n",
    "    \n",
    "print('making instance')\n",
    "X = Spam()\n",
    "print('data:', X.data, X.meth(2))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "可以使用普通的超类继承来获取这个编码模型中的调用拦截器——这里的超类基本上与 type 的作用相同，至少在元类调度方面是这样的。  \n",
    "\n",
    "尽管这种替代形式有效，但是大多数元类通过重新定义 type 超类的 `__new__` 和 `__init__` 来完成它们的工作。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**用元类重载类创建调用**  \n",
    "\n",
    "由于元类参与普通的 OOP 机制，所以通过重新定义 type 对象的 `__call__`，元类也可以直接捕捉类语句末尾的创建调用。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "making metaclass\n",
      "In SuperMeta.init: \n",
      "...SubMeta\n",
      "...(<class 'type'>,)\n",
      "...{'__module__': '__main__', '__qualname__': 'SubMeta', '__new__': <function SubMeta.__new__ at 0x0000027BA26AB7B8>, '__init__': <function SubMeta.__init__ at 0x0000027BA26C7048>}\n",
      "...init class object: ['__module__', '__new__', '__init__', '__doc__']\n",
      "making class\n",
      "In SuperMeta.call: \n",
      "...Spam\n",
      "...(<class '__main__.Eggs'>,)\n",
      "...{'__module__': '__main__', '__qualname__': 'Spam', 'data': 1, 'meth': <function Spam.meth at 0x0000027BA26C7840>}\n",
      "In SubMeta.new: \n",
      "...Spam\n",
      "...(<class '__main__.Eggs'>,)\n",
      "...{'__module__': '__main__', '__qualname__': 'Spam', 'data': 1, 'meth': <function Spam.meth at 0x0000027BA26C7840>}\n",
      "In SubMeta.init: \n",
      "...Spam\n",
      "...(<class '__main__.Eggs'>,)\n",
      "...{'__module__': '__main__', '__qualname__': 'Spam', 'data': 1, 'meth': <function Spam.meth at 0x0000027BA26C7840>}\n",
      "...init class object: ['__module__', 'data', 'meth', '__doc__']\n",
      "making instance\n",
      "data: 1 3\n"
     ]
    }
   ],
   "source": [
    "# 类也可以捕捉调用\n",
    "\n",
    "class SuperMeta(type):\n",
    "    def __call__(meta, classname, supers, classdict):\n",
    "        print('In SuperMeta.call: ', classname, supers, classdict, sep='\\n...')\n",
    "        return type.__call__(meta, classname, supers, classdict)\n",
    "    \n",
    "    def __init__(Class, classname, supers, classdict):\n",
    "        print('In SuperMeta.init: ', classname, supers, classdict, sep='\\n...')\n",
    "        print('...init class object:', list(Class.__dict__.keys()))\n",
    "\n",
    "print('making metaclass')\n",
    "class SubMeta(type, metaclass=SuperMeta):\n",
    "    def __new__(meta, classname, supers, classdict):\n",
    "        print('In SubMeta.new: ', classname, supers, classdict, sep='\\n...')\n",
    "        return type.__new__(meta, classname, supers, classdict)\n",
    "    \n",
    "    def __init__(Class, classname, supers, classdict):\n",
    "        print('In SubMeta.init: ', classname, supers, classdict, sep='\\n...')\n",
    "        print('...init class object:', list(Class.__dict__.keys()))\n",
    "\n",
    "class Eggs:\n",
    "    pass\n",
    "\n",
    "print('making class')\n",
    "\n",
    "class Spam(Eggs, metaclass=SubMeta):      # 通过 SuperMeta.__call__ 调用 SubMeta\n",
    "    data = 1\n",
    "    def meth(self, arg):\n",
    "        return self.data + arg\n",
    "    \n",
    "print('making instance')\n",
    "X = Spam()\n",
    "print('data:', X.data, X.meth(2))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 5. 继承与实例的关系  \n",
    "- **元类继承自 type 类。** 元类通常重新定义 type 类的 `__new__` 和 `__init__`，以定制类创建和初始化，但是，如果它们希望直接捕获类末尾的创建调用的话，它们也可以重新定义 `__call__`。\n",
    "- **元类声明由子类继承。** metaclass=M 声明由该类的子类继承，因此，对于在超类链中继承了这一声明的每个类的构建，该元类都将运行。\n",
    "- **元类属性没有由类实例继承。**由于类是元类的实例，所以元类中定义的行为应用于类，而不是类随后的实例。实例从它们的类和超类获取行为，但是，不是从任何元类获取行为。\n",
    "- **元类属性通过类获取。**相反，类通过实例关系获取元类的方法。从技术上讲,通过类的 `__class__` 链接获取元类属性就像常规实例从他们的类获取名称，但继承首先通过 `__dict__` 搜索尝试：在一个元类和一个超类中有相同名字可用时，使用超类(继承)版本而不是元类(实例)。但是，类的 `__class__` 不用于它自己的实例：元类属性对它们的实例类可用，但对那些实例类的实例不可用。 \n",
    "\n",
    "例如："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "In MetaOne.new:  Super\n",
      "In MetaOne.new:  Sub\n"
     ]
    }
   ],
   "source": [
    "# 文件 metainstance.py\n",
    "\n",
    "class MetaOne(type):\n",
    "    def __new__(meta, classname, supers, classdict):     # 重新定义 type 方法\n",
    "        print('In MetaOne.new: ', classname)\n",
    "        return type.__new__(meta, classname, supers, classdict)\n",
    "    def toast(self):\n",
    "        return 'toast'\n",
    "\n",
    "class Super(metaclass=MetaOne):         # 元类也通过 subs 继承\n",
    "    def spam(self):                     # MetaOne 运行两次\n",
    "        return 'spam'\n",
    "    \n",
    "class Sub(Super):                       # 超类：继承和实例\n",
    "    def eggs(self):                     # 类继承自超类\n",
    "        return 'eggs'                   # 但不继承自元类"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "当这段代码运行的时候，元类处理**两个**客户类的构建，并且实例继承类属性而**不是**元类属性："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'eggs'"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X = Sub()                 # 常规用户定义类的实例\n",
    "X.eggs()                  # 从 Sub 继承"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'spam'"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X.spam()                  # 从 Super 继承"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "ename": "AttributeError",
     "evalue": "'Sub' object has no attribute 'toast'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mAttributeError\u001b[0m                            Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-4-bf6b1eddb3ac>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mX\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mtoast\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m                 \u001b[1;31m# 不继承元类\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mAttributeError\u001b[0m: 'Sub' object has no attribute 'toast'"
     ]
    }
   ],
   "source": [
    "X.toast()                 # 不继承元类"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "相反，类从超类继承名称，也获得元类的名称："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'eggs'"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "Sub.eggs(X)                # 自己的方法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'spam'"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "Sub.spam(X)                # 继承自 Super"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'toast'"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "Sub.toast()                # 从元类获得"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "toast() takes 1 positional argument but 2 were given",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-8-8c5cbd1d68c4>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mSub\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mtoast\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mX\u001b[0m\u001b[1;33m)\u001b[0m               \u001b[1;31m# 不是一个常规类方法\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m: toast() takes 1 positional argument but 2 were given"
     ]
    }
   ],
   "source": [
    "Sub.toast(X)               # 不是一个常规类方法"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "注意，当我们传入一个实例时，前面最后一个调用是如何失败的，因为该名称解析为一个元类方法，而不是一个普通的类方法。实际上，从对象获取名称及其源在这里都非常重要。从元类获取的方法绑定到主体类，而从常规类获取的方法如果通过类获取，则不绑定；如果通过实例获取，则绑定:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<bound method MetaOne.toast of <class '__main__.Sub'>>"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "Sub.toast"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<function __main__.Super.spam(self)>"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "Sub.spam"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<bound method Super.spam of <__main__.Sub object at 0x0000023E37B57DA0>>"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X.spam"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5.1 元类 VS 超类  \n",
    "A 元类的实例 B 可以获取 A 的属性，但是 B 自己的实例不能继承该属性。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "class A(type): attr = 1\n",
    "class B(metaclass=A): pass       # B 是 meta 实例，获取 meta 属性\n",
    "I = B()                          # I 继承类而不是元类\n",
    "B.attr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "ename": "AttributeError",
     "evalue": "'B' object has no attribute 'attr'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mAttributeError\u001b[0m                            Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-2-3a1e9156cedd>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mI\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mattr\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mAttributeError\u001b[0m: 'B' object has no attribute 'attr'"
     ]
    }
   ],
   "source": [
    "I.attr"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "如果 A 由元类转变成超类，则 B 的实例继承了超类 A 的属性。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "class A: attr = 1\n",
    "class B(A): pass              # I 继承类和超类\n",
    "I = B()\n",
    "B.attr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "I.attr"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "事实上，类通过 `__class__` 获取元类属性，以同样的方式，常规实例通过 `__class__` 也继承了。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "__main__.B"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "I.__class__"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "I.__class__.attr"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 6. 元类方法  \n",
    "元类中的方法处理他们的实例 —— 类，不使用常规实例对象的 \"self\"，而是类自身。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<bound method A.x of <class '__main__.B'>>"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "class A(type):\n",
    "    def x(cls): print('ax', cls)         # A 元类\n",
    "    def y(cls): print('ay', cls)         # y 被实例 B 重写\n",
    "\n",
    "class B(metaclass=A):\n",
    "    def y(self): print('by', self)       # A 常规类\n",
    "    def z(self): print('bz', self)       # 命名空间字典有 y 和 z\n",
    "\n",
    "B.x                                      # 从元类获取 x"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<function __main__.B.y(self)>"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "B.y                                      # y 和 z 在类中定义"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<function __main__.B.z(self)>"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "B.z"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ax <class '__main__.B'>\n"
     ]
    }
   ],
   "source": [
    "B.x()                                    # 元类方法调用：获得 cls"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "by <__main__.B object at 0x000001B4008A32B0>\n"
     ]
    }
   ],
   "source": [
    "I = B()                                  # 实例方法调用：获得 inst\n",
    "I.y()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "bz <__main__.B object at 0x000001B4008A32B0>\n"
     ]
    }
   ],
   "source": [
    "I.z()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "ename": "AttributeError",
     "evalue": "'B' object has no attribute 'x'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mAttributeError\u001b[0m                            Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-16-9a76b1cbc1f5>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mI\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mx\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mAttributeError\u001b[0m: 'B' object has no attribute 'x'"
     ]
    }
   ],
   "source": [
    "I.x()                                     # 实例无法看见元类名称"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6.1 元类方法 VS 类方法  \n",
    "虽然它们在继承可见性上有所不同，很像类方法，但是元类方法是用来管理类级数据的。元类方法只能通过类访问，并且不需要显式的 classmethod 类级数据声明来绑定类。换句话说，元类方法可以被认为是隐式类方法："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "33"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "class A(type):\n",
    "    def a(cls):                         # 元类方法：获得类\n",
    "        cls.x = cls.y + cls.z\n",
    "        \n",
    "class B(metaclass=A):\n",
    "    y, z = 11, 22\n",
    "    @classmethod                         # 类方法：获得类\n",
    "    def b(cls):\n",
    "        return cls.x\n",
    "    \n",
    "B.a()                                   # 调用元类方法，仅对类可见\n",
    "B.x                                     # 在 B 上创建类数据，通过常规实例获取"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(33, 11, 22)"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "I = B()\n",
    "I.x, I.y, I.z"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "33"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "I.b()                                   # 类方法：发送类，而不是实例；对实例可见"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "ename": "AttributeError",
     "evalue": "'B' object has no attribute 'a'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mAttributeError\u001b[0m                            Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-21-8fe21644d0e1>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mI\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0ma\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mAttributeError\u001b[0m: 'B' object has no attribute 'a'"
     ]
    }
   ],
   "source": [
    "I.a()                                   # 仅可通过类访问元类方法"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6.2 元类方法中的操作符重载  \n",
    "元类也可以使用操作符重载来使内置操作适用于它们的实例类。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'s'"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "class A(type):\n",
    "    def __getitem__(cls, i):        # 用于处理类的元类方法\n",
    "        return cls.data[i]      \n",
    "    \n",
    "class B(metaclass=A):\n",
    "    data = 'spam'\n",
    "    \n",
    "B[0]                                # 元类实例名称：仅对类可见"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<bound method A.__getitem__ of <class '__main__.B'>>"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "B.__getitem__"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "('spam', 'spam')"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "I = B()\n",
    "I.data, B.data                      # 常规继承名称：对实例和类都可见"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "'B' object does not support indexing",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-25-0e54f79f1ac7>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mI\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m: 'B' object does not support indexing"
     ]
    }
   ],
   "source": [
    "I[0]                                # 类实例不继承元类方法"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 7. 示例：向类添加方法  \n",
    "## 7.1 手动扩展  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Ni!Ni!\n",
      "Ni!Ni!Ni!Ni!\n",
      "baconham\n",
      "ni?ni?ni?ni?\n",
      "baconham\n"
     ]
    }
   ],
   "source": [
    "class Client1:\n",
    "    def __init__(self, value):\n",
    "        self.value = value\n",
    "    def spam(self):\n",
    "        return self.value * 2\n",
    "\n",
    "class Client2:\n",
    "    value = 'ni?'\n",
    "    \n",
    "def eggsfunc(obj):\n",
    "    return obj.value * 4\n",
    "\n",
    "def hamfunc(obj, value):\n",
    "    return value + 'ham'\n",
    "\n",
    "Client1.eggs = eggsfunc\n",
    "Client1.ham = hamfunc\n",
    "\n",
    "Client2.eggs = eggsfunc\n",
    "Client2.ham = hamfunc\n",
    "\n",
    "X = Client1('Ni!')\n",
    "print(X.spam())\n",
    "print(X.eggs())\n",
    "print(X.ham('bacon'))\n",
    "\n",
    "Y = Client2()\n",
    "print(Y.eggs())\n",
    "print(Y.ham('bacon'))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "方法总是在类创建之后分配给一个类，只要分配的方法是带有一个额外的第一个参数以接收主体 self 示例的函数，这个参数可以用来访问类实例中可用的状态信息，即便函数独立于类定义。  \n",
    "\n",
    "这种方法在独立的情况下工作得很好，并且可以在运行时任意地填充一个类。但它有一个潜在的主要缺点，对于需要这些方法的每个类，我们必须重复扩展代码。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 7.2 基于元类的扩展  \n",
    "通过这种方式，我们避免了对任何给定的类修改扩展的机会。此外，在单独位置编写扩展更好地支持了未来的修改——集合中的所有类都将自动接收修改。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Ni!Ni!\n",
      "Ni!Ni!Ni!Ni!\n",
      "baconham\n",
      "ni?ni?ni?ni?\n",
      "baconham\n"
     ]
    }
   ],
   "source": [
    "def eggsfunc(obj):\n",
    "    return obj.value * 4\n",
    "\n",
    "def hamfunc(obj, value):\n",
    "    return value + 'ham'\n",
    "\n",
    "class Extender(type):\n",
    "    def __new__(meta, classname, supers, classdict):\n",
    "        classdict['eggs'] = eggsfunc\n",
    "        classdict['ham'] = hamfunc\n",
    "        return type.__new__(meta, classname, supers, classdict)\n",
    "    \n",
    "class Client1(metaclass=Extender):\n",
    "    def __init__(self, value):\n",
    "        self.value = value\n",
    "    def spam(self):\n",
    "        return self.value * 2\n",
    "    \n",
    "class Client2(metaclass=Extender):\n",
    "    value = 'ni?'\n",
    "    \n",
    "X = Client1('Ni!')\n",
    "print(X.spam())\n",
    "print(X.eggs())\n",
    "print(X.ham('bacon'))\n",
    "\n",
    "Y = Client2()\n",
    "print(Y.eggs())\n",
    "print(Y.ham('bacon'))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 7.3 元类 VS 类装饰器：第二回合  \n",
    "类装饰器常常和元类在功能上有重合。\n",
    "- 在新类创建后，在 class 语句的末尾，类装饰器把类名重新绑定到一个函数的结果。\n",
    "- 元类通过在一条 class 语句的末尾把类对象创建过程路由到一个对象来工作。\n",
    "\n",
    "**基于装饰器的扩展**  \n",
    "\n",
    "装饰器大致与元类的 `__init__` 方法对应。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Ni!Ni!\n",
      "Ni!Ni!Ni!Ni!\n",
      "baconham\n",
      "ni?ni?ni?ni?\n",
      "baconham\n"
     ]
    }
   ],
   "source": [
    "def eggsfunc(obj):\n",
    "    return obj.value * 4\n",
    "\n",
    "def hamfunc(obj, value):\n",
    "    return value + 'ham'\n",
    "\n",
    "def Extender(aClass):\n",
    "    aClass.eggs = eggsfunc        # 管理类，而不是实例\n",
    "    aClass.ham = hamfunc          # 和元类 __init__ 相当\n",
    "    return aClass\n",
    "\n",
    "@Extender\n",
    "class Client1:      # Client1 = Extender(Client1)\n",
    "    def __init__(self, value):          # 在类声明最后重新绑定\n",
    "        self.value = value\n",
    "    def spam(self):\n",
    "        return self.value * 2\n",
    "\n",
    "@Extender\n",
    "class Client2:\n",
    "    value = 'ni?'\n",
    "    \n",
    "X = Client1('Ni!')\n",
    "print(X.spam())\n",
    "print(X.eggs())\n",
    "print(X.ham('bacon'))\n",
    "\n",
    "Y = Client2()\n",
    "print(Y.eggs())\n",
    "print(Y.ham('bacon'))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**管理实例而不是类**  \n",
    "\n",
    "类装饰器常常可以和元类一样充当**类管理**角色。元类往往和装饰器一样充当**实例管理**的角色，但是，这更复杂一点。\n",
    "- 类装饰器可以管理类和实例。\n",
    "- 元类可以管理类和实例，但是管理实例需要一些额外工作。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Trace: name\n",
      "Bob\n",
      "Trace: pay\n",
      "2000\n"
     ]
    }
   ],
   "source": [
    "def Tracer(aClass):                           # 在 @ 装饰时\n",
    "    class Wrapper:\n",
    "        def __init__(self, *args, **kargs):   # 在实例创建时\n",
    "            self.wrapped = aClass(*args, **kargs) \n",
    "        def __getattr__(self, attrname):\n",
    "            print('Trace:', attrname)\n",
    "            return getattr(self.wrapped, attrname)\n",
    "    return Wrapper\n",
    "\n",
    "@Tracer\n",
    "class Person:                                 # Person = Tracer(Person)\n",
    "    def __init__(self, name, hours, rate):\n",
    "        self.name = name\n",
    "        self.hours = hours\n",
    "        self.rate = rate\n",
    "    def pay(self):\n",
    "        return self.hours * self.rate\n",
    "\n",
    "bob = Person('Bob', 40, 50)                   # bob 是一个 Wrapper\n",
    "print(bob.name)                               # Wrapper 嵌入 Person\n",
    "print(bob.pay())                              # 触发 __getattr__"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "装饰器使用类名重新绑定来把实例对象包装到一个对象中，该对象在输出中给出跟踪行。  \n",
    "\n",
    "元类明确地设计来管理类对象创建，并且它们有一个为此目的而设计的接口。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Trace: name\n",
      "Bob\n",
      "Trace: pay\n",
      "2000\n"
     ]
    }
   ],
   "source": [
    "def Tracer(classname, supers, classdict):     # 类创建时\n",
    "    aClass = type(classname, supers, classdict)   # 创建客户类\n",
    "    class Wrapper:\n",
    "        def __init__(self, *args, **kargs):   # 在实例创建时\n",
    "            self.wrapped = aClass(*args, **kargs) \n",
    "        def __getattr__(self, attrname):\n",
    "            print('Trace:', attrname)\n",
    "            return getattr(self.wrapped, attrname)\n",
    "    return Wrapper\n",
    "\n",
    "class Person(metaclass=Tracer):              # 创建带 Tracer 的 Person\n",
    "    def __init__(self, name, hours, rate):\n",
    "        self.name = name\n",
    "        self.hours = hours\n",
    "        self.rate = rate\n",
    "    def pay(self):\n",
    "        return self.hours * self.rate\n",
    "\n",
    "bob = Person('Bob', 40, 50)                   # bob 是一个 Wrapper\n",
    "print(bob.name)                               # Wrapper 嵌入 Person“”\n",
    "print(bob.pay())                              # 触发 __getattr__"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这依赖于两个技巧。首先，它必须使用一个简单的函数而不是一个类，因为 type 子类必须附加给对象创建协议。其次，必须通过手动调用 type 来手动创建主体类；它需要返回一个实例包装器，但是元类也负责创建和返回主体类。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 8. 示例：对方法应用装饰器  \n",
    "## 8.1 用装饰器手动跟踪"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "def tracer(func):                     # 使用函数，而不是类的 __call__\n",
    "    calls = 0\n",
    "    def onCall(*args, **kwargs):\n",
    "        nonlocal calls\n",
    "        calls += 1\n",
    "        print('call %s to %s' % (calls, func.__name__))\n",
    "        return func(*args, **kwargs)\n",
    "    return onCall\n",
    "\n",
    "import time\n",
    "def timer(label='', trace=True):\n",
    "    def onDecorator(func): \n",
    "        def onCall(*args, **kargs):\n",
    "            start = time.clock()\n",
    "            result = func(*args, **kargs)\n",
    "            elapsed = time.clock() - start\n",
    "            onCall.alltime += elapsed\n",
    "            if trace:\n",
    "                format = '%s%s: %.5f, %.5f'\n",
    "                values = (label, func.__name__, elapsed, onCall.alltime)\n",
    "                print(format % values)\n",
    "            return result\n",
    "        onCall.alltime = 0\n",
    "        return onCall\n",
    "    return onDecorator"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "call 1 to __init__\n",
      "call 2 to __init__\n",
      "Bob Smith Sue Jones\n",
      "call 1 to giveRaise\n",
      "110000.00\n",
      "call 1 to lastName\n",
      "call 2 to lastName\n",
      "Smith Jones\n"
     ]
    }
   ],
   "source": [
    "class Person:\n",
    "    @tracer\n",
    "    def __init__(self, name, pay):\n",
    "        self.name = name\n",
    "        self.pay = pay\n",
    "\n",
    "    @tracer\n",
    "    def giveRaise(self, percent):   # giveRaise = tracer(giverRaise)\n",
    "        self.pay *= (1.0 + percent) # onCall 记住 giveRaise\n",
    "\n",
    "    @tracer\n",
    "    def lastName(self):             # lastName = tracer(lastName)\n",
    "        return self.name.split()[-1]\n",
    "\n",
    "bob = Person('Bob Smith', 50000)\n",
    "sue = Person('Sue Jones', 100000)\n",
    "print(bob.name, sue.name)\n",
    "sue.giveRaise(.10)                   # 运行 onCall(sue, .10)\n",
    "print('%.2f' % sue.pay)\n",
    "print(bob.lastName(), sue.lastName()) # 运行 onCall(bob), 记住 lastName"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 8.2 用元类和装饰器跟踪  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "call 1 to __init__\n",
      "call 2 to __init__\n",
      "Bob Smith Sue Jones\n",
      "call 1 to giveRaise\n",
      "110000.00\n",
      "call 1 to lastName\n",
      "call 2 to lastName\n",
      "Smith Jones\n"
     ]
    }
   ],
   "source": [
    "from types import FunctionType\n",
    "\n",
    "class MetaTrace(type):\n",
    "    def __new__(meta, classname, supers, classdict):\n",
    "        for attr, attrval in classdict.items():\n",
    "            if type(attrval) is FunctionType:           # 方法?\n",
    "                classdict[attr] = tracer(attrval)       # 装饰\n",
    "        return type.__new__(meta, classname, supers, classdict) # 创建类\n",
    "\n",
    "class Person(metaclass=MetaTrace):\n",
    "    def __init__(self, name, pay):\n",
    "        self.name = name\n",
    "        self.pay = pay\n",
    "    def giveRaise(self, percent):\n",
    "        self.pay *= (1.0 + percent)\n",
    "    def lastName(self):\n",
    "        return self.name.split()[-1]\n",
    "\n",
    "bob = Person('Bob Smith', 50000)\n",
    "sue = Person('Sue Jones', 100000)\n",
    "print(bob.name, sue.name)\n",
    "sue.giveRaise(.10)\n",
    "print('%.2f' % sue.pay)\n",
    "print(bob.lastName(), sue.lastName())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在类创建的时候，元类自动把函数装饰器应用于每个方法，并且函数装饰器自动拦截方法调用，以便在此输出中打印出跟踪消息。  \n",
    "\n",
    "## 8.3 把任何装饰器应用于方法  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "call 1 to __init__\n",
      "call 2 to __init__\n",
      "Bob Smith Sue Jones\n",
      "call 1 to giveRaise\n",
      "110000.00\n",
      "call 1 to lastName\n",
      "call 2 to lastName\n",
      "Smith Jones\n"
     ]
    }
   ],
   "source": [
    "from types import FunctionType\n",
    "\n",
    "def decorateAll(decorator):\n",
    "    class MetaDecorate(type):\n",
    "        def __new__(meta, classname, supers, classdict):\n",
    "            for attr, attrval in classdict.items():\n",
    "                if type(attrval) is FunctionType:\n",
    "                    classdict[attr] = decorator(attrval)\n",
    "            return type.__new__(meta, classname, supers, classdict)\n",
    "    return MetaDecorate\n",
    "\n",
    "class Person(metaclass=decorateAll(tracer)):   # 应用装饰器于所有方法\n",
    "    def __init__(self, name, pay):\n",
    "        self.name = name\n",
    "        self.pay = pay\n",
    "    def giveRaise(self, percent):\n",
    "        self.pay *= (1.0 + percent)\n",
    "    def lastName(self):\n",
    "        return self.name.split()[-1]\n",
    "\n",
    "bob = Person('Bob Smith', 50000)\n",
    "sue = Person('Sue Jones', 100000)\n",
    "print(bob.name, sue.name)\n",
    "sue.giveRaise(.10)\n",
    "print('%.2f' % sue.pay)\n",
    "print(bob.lastName(), sue.lastName())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "要对方法应用一种不同的装饰器，我们只要在类标题行替换装饰器名称。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Person(metaclass=decorateAll(tracer)):         # 应用 tracer\n",
    "class Person(metaclass=decorateAll(timer())):        # 应用计时器\n",
    "class Person(metaclass=decorateAll(timer(label='**')))   # 装饰器参数"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 8.4 元类 VS 类装饰器：第三回合\n",
    "它定义并使用一个**类装饰器**，该装饰器把一个**函数装饰器**应用于一个类的所有方法。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "call 1 to __init__\n",
      "call 2 to __init__\n",
      "Bob Smith Sue Jones\n",
      "call 1 to giveRaise\n",
      "110000.00\n",
      "call 1 to lastName\n",
      "call 2 to lastName\n",
      "Smith Jones\n"
     ]
    }
   ],
   "source": [
    "def decorateAll(decorator):\n",
    "    def DecoDecorate(aClass):\n",
    "        for attr, attrval in aClass.__dict__.items():\n",
    "            if type(attrval) is FunctionType:\n",
    "                setattr(aClass, attr, decorator(attrval)) # 不是 __dict__\n",
    "        return aClass\n",
    "    return DecoDecorate\n",
    "\n",
    "@decorateAll(tracer)                             # 使用类装饰器\n",
    "class Person:                                    # 应用 func 装饰器到方法\n",
    "    def __init__(self, name, pay):               # Person = decorateAll(..)(Person)\n",
    "        self.name = name                         # Person = DecoDecorate(Person)\n",
    "        self.pay = pay\n",
    "    def giveRaise(self, percent):\n",
    "        self.pay *= (1.0 + percent)\n",
    "    def lastName(self):\n",
    "        return self.name.split()[-1]\n",
    "\n",
    "bob = Person('Bob Smith', 50000)\n",
    "sue = Person('Sue Jones', 100000)\n",
    "print(bob.name, sue.name)\n",
    "sue.giveRaise(.10)\n",
    "print('%.2f' % sue.pay)\n",
    "print(bob.lastName(), sue.lastName())"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
